package com.zlq.iwork.view;

import java.util.Calendar;

import com.zlq.iwork.R;
import com.zlq.iwork.bean.Note;
import com.zlq.iwork.bean.NoteDao;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

public class WorkAddActivity extends BaseActivity implements OnClickListener {

	private TextView tv_cancle;
	private TextView tv_save;
	private EditText et_note;
	private TextView tv_date;

	private static final int DATE_DIALOG = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_work_add);
		findView();
	}

	public void findView() {
		tv_cancle = (TextView) findViewById(R.id.tv_cancle);
		tv_save = (TextView) findViewById(R.id.tv_save);
		tv_date = (TextView) findViewById(R.id.tv_date);
		et_note = (EditText) findViewById(R.id.et_note);
		tv_cancle.setOnClickListener(this);
		tv_save.setOnClickListener(this);
		tv_date.setOnClickListener(this);
		Calendar c = Calendar.getInstance();
		tv_date.setText(c.get(Calendar.YEAR) + "-"
				+ (c.get(Calendar.MONTH) + 1) + "-"
				+ c.get(Calendar.DAY_OF_MONTH));

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.tv_cancle:
			this.finish();
			break;
		case R.id.tv_save:
			save();

			break;
		case R.id.tv_date:
			showDialog(DATE_DIALOG);
			break;
		default:
			break;
		}
	}

	public void save() {
		Note note = new Note();
		note.setNote(et_note.getText().toString());
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(this);

		String name = sp.getString("p_name", "");
		note.setUserid(name);
		note.setDate(tv_date.getText().toString());
		note.setCurDate(System.currentTimeMillis());
		NoteDao dao = new NoteDao(this);
		dao.add(note);
		setResult(RESULT_OK);
		finish();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case DATE_DIALOG:
			Calendar c = Calendar.getInstance();
			dialog = new DatePickerDialog(this,
					new DatePickerDialog.OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							tv_date.setText(year + "-" + (monthOfYear + 1)
									+ "-" + dayOfMonth);

						}
					}, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
					c.get(Calendar.DAY_OF_MONTH));
			break;

		default:
			break;
		}
		return dialog;
	}

}
